CC := avr-gcc
OBJCOPY := avr-objcopy
MCU := at90usb1287
PROGRAMMER := sudo dfu-programmer $(MCU)

CFLAGS := $(CFLAGS) -mmcu=$(MCU) -DF_CPU=8000000UL -fsigned-char
CFLAGS := $(CFLAGS) -O2 -gdwarf-2
CFLAGS := $(CFLAGS) -Ibase -Icommon -Ihover -Irtos
CFLAGS := $(CFLAGS) -Wall -Wextra
LDFLAGS := $(LDFLAGS) -mmcu=$(MCU) -nostartfiles
LDFLAGS := $(LDFLAGS) -gdwarf-2
#HEXFLAGS := -R .eeprom

COMMONCFILES := $(wildcard common/*.c) $(wildcard rtos/*.c)
BASECFILES := $(wildcard base/*.c) $(COMMONCFILES)
HOVERCFILES := $(wildcard hover/*.c) $(COMMONCFILES)

BASEOBJ := $(BASECFILES:%.c=build/%.o)
HOVEROBJ := $(HOVERCFILES:%.c=build/%.o)

BASETARGET := build/base
HOVERTARGET := build/hover
all: base hover
base: $(BASETARGET).hex
hover: $(HOVERTARGET).hex

$(BASETARGET).elf: $(BASEOBJ)
$(HOVERTARGET).elf: $(HOVEROBJ)

eraseboard:
	$(PROGRAMMER) erase

flashbase: $(BASETARGET).hex eraseboard
	$(PROGRAMMER) flash $<

flashhover: $(HOVERTARGET).hex eraseboard
	$(PROGRAMMER) flash $<

tags: $(COMMONCFILES) $(BASECFILES) $(HOVERCFILES)
	ctags -R .

build/%.o: %.c Makefile
	$(CC) $(CFLAGS) -MMD -MP -MF "build/$*.d" -c -o $@ $<

%.hex: %.elf
	$(OBJCOPY) -O ihex $(HEX_FLAGS) $< $@

%.elf:
	$(CC) $(LDFLAGS) -o $@ $^ $(LIBS)

clean:
	$(RM) -R build

-include $(shell mkdir -p build/common build/base build/hover build/rtos) $(wildcard dep/*/*)

